import os
import subprocess

from django.conf import settings

class ExecJs:
    
    __project_path = os.path.join(os.path.dirname(settings.BASE_DIR), "wxmp/wxmatch")

    @staticmethod
    def upload(miniprogram, callback):
        # 设置小程序的服务器地址，在settings/data.js
        dir = "".join((ExecJs.__project_path, "//settings//"))
        cmd_data = ' cat {source} > {target} && sed -i "s|domain|{domain}|g" {target}'.format(source=dir+'data.bak',target=dir+'data.js',domain=miniprogram["host"])
        
        # popen返回文件对象，跟open操作一样
        cmd_upload = "miniprogram-ci upload --pp {project}  --pkp {upload_key}   --appid {appid}  --uv {ver}   -r 1   --enable-es6 true --locales zh --use-cos --enable-minify --enable-code-protect;".format(
            project=ExecJs.__project_path,
            upload_key=miniprogram["key_path"],
            appid=miniprogram["appid"],
            ver=miniprogram["ver"],
        )
        cmd_str = " && ".join((cmd_data, cmd_upload))
        #cmd_str = cmd_upload

        try:
            # 定义日志序号
            num = 1;
            # scheduler_order = "top -u ybtao"
            return_info = subprocess.Popen(cmd_str, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            while True:
                next_line = return_info.stdout.readline()
                return_line = next_line.decode("utf-8", "ignore")
                if return_line == '' and return_info.poll() != None:
                    callback(msg ="{num}:{msg}".format(num=num,msg=""),type=1)
                    break
                callback(msg ="{num}:{msg}".format(num=num,msg=return_line),type= 0)
                num += 1;

            returncode = return_info.wait()
            if returncode:
                raise subprocess.CalledProcessError(returncode, return_info)
        except Exception as e:
            callback(msg ="{num}:{msg}".format(num=num,msg=e),type=-1)


